<?php

// phpMyRealty 3
//
// File Name: findusers.php
// File Location : ./admin/
//
// Copyright (c)2009 phpMyRealty.com
//
// e-mail: support@phpMyRealty.com

// Include configuration file and general functions
define('PMR', 'true');
define('PMRADMIN', 'true');

include ( '.././config.php' );
include ( PATH . '/defaults.php' );

// ----------------------------------------------------------------------
// ADMIN PANEL / FIND USERS

// Title tag
$title = $lang['Realtor_Search'];

// Template header
include ( PATH . '/admin/template/header.php' );

// If logged we can start the page output
if (adminAuth($session->fetch('adminlogin'), $session->fetch('adminpassword')))

 {
  // Include Navigation Panel
  include ( PATH . '/admin/navigation.php' );
 
  // Make sure this administrator have access to this script
  adminPermissionsCheck('manage_users', $session->fetch('adminlogin')) or error ('Critical Error', 'Incorrect privileges');

  // Remove user function
  if (isset($_GET['req']) && $_GET['req'] == 'remove' && isset($_GET['userid']) && eregi('^[0-9]+$', $_GET['userid']))

   {

    echo table_header ( $lang['Information'] );

    $sql = 'SELECT * FROM ' . USERS_TABLE  . ' WHERE id = ' . $_GET['userid'] . ' LIMIT 1';
    $r_user = $db->query ( $sql ) or error ('Critical Error' , mysql_error());
    $f_user = $db->fetcharray ($r_user);

    removeuser(intval($_GET['userid']));

    echo $lang['Admin_Realtor_Removed'];

//

    $mail = new PHPMailer();

    if(PHPMAILER == '3') {
     $mail->IsSMTP(); // set mailer to use SMTP
     $mail->Host = $smtp['host'];  // specify main and backup server
     $mail->SMTPAuth = true;     // turn on SMTP authentication
     $mail->Username = $smtp['login'];  // SMTP username
     $mail->Password = $smtp['password']; // SMTP password
    }
    elseif(PHPMAILER == '2') {
     $mail->IsSendmail(); // set mailer to use SMTP
    }
    else {
    }

    $mail->From = $conf['general_e_mail'];
    $mail->FromName = $conf['general_e_mail_name'];

    $mail->AddAddress($f_user['email']);

    $lang['User_Rejected_Notification_Subject'] = str_replace('{website_name}', $conf['website_name'], $lang['User_Rejected_Notification_Subject']);

    $mail->Subject = $lang['User_Rejected_Notification_Subject'];

    // Replacing the variable names
    $lang['User_Rejected_Notification_Mail'] = str_replace('{website_name}', $conf['website_name'], $lang['User_Rejected_Notification_Mail']);

    $mail->MsgHTML = $lang['User_Rejected_Notification_Mail'];
    $mail->AltBody = removehtml($lang['User_Rejected_Notification_Mail']);

    $mail->Send();

    echo table_footer ();

   }

  // Approve user function
  if (isset($_GET['req']) && $_GET['req'] == 'approve' && isset($_GET['userid']) && eregi('^[0-9]+$', $_GET['userid']))
   {

    echo table_header ( $lang['Information'] );

    $sql = 'UPDATE ' . USERS_TABLE . ' SET approved = 1 WHERE id = ' . $_GET['userid'] . ' LIMIT 1';  
    $db->query($sql) or error ( 'Critical Error', mysql_error() );

    echo $lang['Admin_User_Approved'];

//

    $mail = new PHPMailer();

    if(PHPMAILER == '3') {
     $mail->IsSMTP(); // set mailer to use SMTP
     $mail->Host = $smtp['host'];  // specify main and backup server
     $mail->SMTPAuth = true;     // turn on SMTP authentication
     $mail->Username = $smtp['login'];  // SMTP username
     $mail->Password = $smtp['password']; // SMTP password
    }
    elseif(PHPMAILER == '2') {
     $mail->IsSendmail(); // set mailer to use SMTP
    }
    else {
    }

    $mail->From = $conf['general_e_mail'];
    $mail->FromName = $conf['general_e_mail_name'];

    $sql = 'SELECT * FROM ' . USERS_TABLE  . ' WHERE id = ' . $_GET['userid'] . ' LIMIT 1';
    $r_user = $db->query ( $sql ) or error ('Critical Error' , mysql_error());
    $f_user = $db->fetcharray ($r_user);

    $mail->AddAddress($f_user['email']);

    $lang['User_Realtor_Notification_Subject'] = str_replace('{website_name}', $conf['website_name'], $lang['User_Realtor_Notification_Subject']);
    $mail->Subject = $lang['User_Realtor_Notification_Subject'];

    // Replacing the variable names
    $lang['User_Realtor_Notification_Mail'] = str_replace('{website_name}', $conf['website_name'], $lang['User_Realtor_Notification_Mail']);
    $lang['User_Realtor_Notification_Mail'] = str_replace('{first_name}', $f_user['first_name'], $lang['User_Realtor_Notification_Mail']);
    $lang['User_Realtor_Notification_Mail'] = str_replace('{last_name}', $f_user['last_name'], $lang['User_Realtor_Notification_Mail']);
    $lang['User_Realtor_Notification_Mail'] = str_replace('{company}', $f_user['company_name'], $lang['User_Realtor_Notification_Mail']);
    $lang['User_Realtor_Notification_Mail'] = str_replace('{address}', $f_user['address'] . ' ' . $f_user['city'] . ' ' . $f_user['zip'] . ' ' . getnamebyid(LOCATIONS_TABLE, $f_user['location']), $lang['User_Realtor_Notification_Mail']);

    $mail->MsgHTML = $lang['User_Realtor_Notification_Mail'];
    $mail->AltBody = removehtml($lang['User_Realtor_Notification_Mail']);

    $mail->Send();

    echo table_footer ();

   }

  // Define an array of all the search elements
  $search = array();

  // If this is the first time we call this script
  // we use the _POST'ed variable, if not, we use
  // _GET method
  if (isset($_POST['realtor_search']))
   $search = array_map ('safehtml', $_POST);
  else
   {
    $search = array_map ('rawurldecode', $_GET);
    $search = array_map ('safehtml', $search);
   }

  // Generate GET vars and push it into the session variable
  // to be able to return to this search page later

  unset ($search['req']);
  unset ($search['userid']);

  $session->varunset('usersearchvariables');
  $searchURL = ''; foreach ($search as $key => $value) $searchURL.= $key . '=' . rawurlencode($value) . '&';
  $session->set('usersearchvariables', $searchURL);
 
  // Pagination
  if (isset($_GET['page'])) $page = $_GET['page']; else $page = 0;
  unset($search['page']);

  $results_page = $page * $conf['search_results'];

  // Errors output if needed

  // Initially we think that no errors were found
  $count_error = 0;

/*

// If keyword was not specified we stop processing
if (isset($search['realtor_description']) && empty($search['realtor_description']))
 { echo $lang['Field_Empty'] . ' <strong><span class="warning">' . $lang['Search_Keyword'] . '</span></strong><br />'; $count_error++; }
//

*/

  // If there were errors found we print the 
  // errors descriptions
  if ($count_error > 0)
   {
    echo table_header ( $lang['Information'] );

    echo $lang['Errors_Found'] . ': ' . $count_error;

    echo table_footer ();
   }

  // Output the results
  //
  // If no errors found we output the results

  $usersearch = $session->fetch('usersearchvariables');

  if ($count_error == 0 && !empty($usersearch))
   {

    // Generate the SQL query

    $sql = 'SELECT * from ' . USERS_TABLE . ' WHERE ';

    $sql.= 'id IS NOT NULL ';

    if (isset($search['id']) && !empty($search['id'])) 
     $sql.= 'AND id = ' . $search['id'] . ' ';

    if (isset($search['realtor_approved']) && !empty($search['realtor_approved'])) 
     $sql.= 'AND approved = 0 ';
  
    if (isset($search['realtor_updated']) && !empty($search['realtor_updated']) && isset($search['realtor_updated_days']) && !empty($search['realtor_updated_days']))
     $sql.= 'AND ( (TO_DAYS(NOW()) - TO_DAYS(date_updated)) <= ' . $search['realtor_updated_days']. ' ) ';
 
    if (isset($search['realtor_first_name']) && !empty($search['realtor_first_name'])) 
     $sql.= 'AND first_name LIKE "%' . $search['realtor_first_name'] . '%" ';

    if (isset($search['realtor_last_name']) && !empty($search['realtor_last_name'])) 
     $sql.= 'AND last_name LIKE "%' . $search['realtor_last_name'] . '%" ';

    if (isset($search['realtor_company_name']) && !empty($search['realtor_company_name'])) 
     $sql.= 'AND company_name LIKE "%' . $search['realtor_company_name'] . '%" ';

    if (isset($search['realtor_description']) && !empty($search['realtor_description'])) 
     $sql.= 'AND description LIKE "%' . $search['realtor_description'] . '%" ';

    if (isset($search['realtor_location']) && $search['realtor_location'] != 'ANY')
     $sql.= 'AND location = ' . $search['realtor_location'] . ' ';
 
    if (isset($search['realtor_city']) && !empty($search['realtor_city'])) 
     $sql.= 'AND city = "' . $search['realtor_city'] . '" ';
 
    if (isset($search['realtor_address']) && !empty($search['realtor_address'])) 
     $sql.= 'AND address LIKE "%' . $search['realtor_address'] . '%" ';
 
    if (isset($search['realtor_zip_code']) && !empty($search['realtor_zip_code'])) 
     $sql.= 'AND zip = "' . $search['realtor_zip_code'] . '" ';
 
    if (isset($search['realtor_phone']) && !empty($search['realtor_phone'])) 
     $sql.= 'AND phone LIKE "%' . $search['realtor_phone'] . '%" ';

    if (isset($search['realtor_fax'])  && !empty($search['realtor_fax'])) 
     $sql.= 'AND fax LIKE "%' . $search['realtor_fax'] . '%" ';

    if (isset($search['realtor_mobile']) && !empty($search['realtor_mobile'])) 
     $sql.= 'AND mobile LIKE "%' . $search['realtor_mobile'] . '%" ';
 
    if (isset($search['realtor_e_mail']) && !empty($search['realtor_e_mail']))
     $sql.= 'AND email = "' . $search['realtor_e_mail'] . '" ';

    if (isset($search['realtor_website']) && !empty($search['realtor_website'])) 
     $sql.= 'AND website LIKE "%' . $search['realtor_website'] . '%" ';
 
    if (isset($search['realtor_login'])  && !empty($search['realtor_login'])) 
     $sql.= 'AND login = "' . $search['realtor_login'] . '" ';
 
    $sql2 = $sql . ' LIMIT ' . $results_page . ', ' . $conf['search_results'];

    // End creating sql query
 
    echo table_header ( $lang['Realtor_Search'] );

    echo '
     <table width="100%" cellpadding="5" cellspacing="0" border="0">
         ';

    $r = $db->query($sql) or error ('Critical Error', mysql_error ());

    $r2 = $db->query($sql2) or error ('Critical Error', mysql_error ());

    if ($db->numrows($r) == 0)
     echo '<p align="center"><span class="warning">' . $lang['Nothing_Found'] . '</span></p>';

    $i = 0;

    $tpl = implode ('', file( PATH . '/admin/template/tpl/user-short.tpl' ));

    while ($f = $db->fetcharray( $r2 ))

     {
 
      // Starting a new template
      $template = new Template;

      // Load user short search results template
      $template->load ( $tpl );

      $f = array_map ( 'if_empty', $f);
 
      // Replace the template variables
      $template->set ( 'edit',  '<a href="' . URL . '/admin/editusers.php?userid=' . $f['id'] . '">' . $lang['Admin_Edit_This'] . '</a>');
      $template->set ( 'remove', '<a href="' . URL . '/admin/findusers.php?req=remove&userid=' . $f['id'] . '&' . $session->fetch('usersearchvariables') . '" onClick="return confirmDelete(\'Are you sure you want to remove this user?\')"><span class="warning">' . $lang['Admin_Remove_This'] . '</span></a>');
 
      if ($f['approved'] == 0 && adminPermissionsCheck('manage_users', $session->fetch('adminlogin')))
       $template->set ( 'approve', '<a href="' . URL . '/admin/findusers.php?req=approve&userid=' . $f['id'] . '&' . $session->fetch('usersearchvariables') . '">' . $lang['Admin_Approve_This'] . '</a>');
      else
       $template->set ( 'approve', $lang['Admin_Approve_This']);

      $sql = 'SELECT COUNT(*) FROM ' . PROPERTIES_TABLE . ' WHERE userid = ' . $f['id'];
      $res = $db->query($sql); 
      $listings = mysql_result ($res, 0, 0);

      if (adminPermissionsCheck('manage_listings', $session->fetch('adminlogin')) && $f['approved'] == 1)
       $template->set ( 'add_listings', '<a href="' . URL . '/admin/addlistings.php?userid=' . $f['id'] . '">' . $lang['Admin_Add_Listings'] . '</a>');
      else
       $template->set ( 'add_listings', $lang['Admin_Add_Listings']);

      if (adminPermissionsCheck('manage_listings', $session->fetch('adminlogin')) && $listings > 0 && $f['approved'] == 1)
       $template->set ( 'edit_listings', '<a href="' . URL . '/admin/findlistings.php?userid=' . $f['id'] . '">' . $lang['Admin_Edit_Listings'] . '</a> (' . $listings . ')');
      else
       $template->set ( 'edit_listings', $lang['Admin_Edit_Listings']);

      $template->set ( 'photo', show_image ('photos', $f['id']) );
      $template->set ( 'first_name', $f['first_name'] );
      $template->set ( 'last_name', $f['last_name'] );
      $template->set ( 'company_name', $f['company_name'] );

      // Cut the description to the size set in config if Java Script
      // is disabled in user browser
      $description = substr($f['description'], 0, $conf['search_description']);
      $description = substr($description, 0, strrpos($description, ' ')) . ' ... ';

      $template->set ( 'description', $description );
 
      unset ($description);

      $template->set ( 'location', getnamebyid ( LOCATIONS_TABLE, $f['location'] ) );
      $template->set ( 'address', $f['address'] );
      $template->set ( 'city', $f['city'] );
      $template->set ( 'zip', $f['zip'] );
      $template->set ( 'phone', $f['phone'] );
      $template->set ( 'fax', $f['fax'] );
      $template->set ( 'mobile', $f['mobile'] );
      $template->set ( 'email', validateemail ( $f['id'], $f['email'] ) );
      $template->set ( 'website', validatewebsite ( $f['id'], $f['website'] ) );
      $template->set ( 'view_user_listings', viewuserlistings ( $f['id'] )  );
 
      $template->set ( 'date_added', printdate($f['date_added']) );
      $template->set ( 'date_updated', printdate($f['date_updated']) );
 
      $template->set ( 'ip_added', $f['ip_added'] );
      $template->set ( 'ip_updated', $f['ip_updated'] );

      $template->set ( 'hits', $f['hits'] );

      $template->set ( 'new', newitem ( USERS_TABLE, $f['id'], $conf['new_days']) );
      $template->set ( 'updated', updateditem ( USERS_TABLE, $f['id'], $conf['updated_days']) );
      $template->set ( 'top', topitem ( $f['rating'], $f['votes'] ) );

      $voting_form = '<form action="' . URL . '/viewuser.php?req=rating&id=' . $f['id'] . '" method="POST"> <select name="vote" onChange="this.form.submit()">   <option value=""> --- </option>   <option value="5">' . $lang['Realtor_Vote_5'] . '</option>    <option value="4">' . $lang['Realtor_Vote_4'] . '</option>    <option value="3">' . $lang['Realtor_Vote_3'] . '</option>    <option value="2">' . $lang['Realtor_Vote_2'] . '</option>    <option value="1">' . $lang['Realtor_Vote_1'] . '</option> </select> </form>';

      $template->set ( 'voting_form', $voting_form );

      $template->set ( 'rating', rating ( $f['rating'], $f['votes'] ) );

      // Set background color
      $bgcolor = ''; // Background color for all odd listings
      $bgcolor2 = $conf['list_background_color_even']; // Background color for all even listings
 
      if ( $i%2 == 0 )
       $template->set ( 'bgcolor', $bgcolor );
      else
       $template->set ( 'bgcolor', $bgcolor2 );

      // Names

      $template->set ( '@first_name', $lang['Realtor_First_Name'] );
      $template->set ( '@last_name', $lang['Realtor_Last_Name'] );
      $template->set ( '@company_name', $lang['Realtor_Company_Name'] );
      $template->set ( '@description', $lang['Realtor_Description'] );
      $template->set ( '@location', $lang['Location'] );
      $template->set ( '@city', $lang['City'] );
      $template->set ( '@address', $lang['Realtor_Address'] );
      $template->set ( '@zip', $lang['Zip_Code'] );
      $template->set ( '@phone', $lang['Realtor_Phone'] );
      $template->set ( '@fax', $lang['Realtor_Fax'] );
      $template->set ( '@mobile', $lang['Realtor_Mobile'] );
      $template->set ( '@email', $lang['Realtor_e_mail'] );
      $template->set ( '@website', $lang['Realtor_Website'] );
      $template->set ( '@date_added', $lang['Date_Added'] );
      $template->set ( '@date_updated', $lang['Date_Updated'] );
      $template->set ( '@hits', $lang['Hits'] );
 
      // Publish template
      $template->publish();
  
      $i++;

     }

    echo '
     </table>  
         ';

    // Pagination

    echo '<br />';
 
    // Generate GET vars and push it into the variable
    $searchURL = ''; foreach ($search as $key => $value) $searchURL.= $key . '=' . rawurlencode($value) . '&';

    $results = $db->numrows( $r );

    if ( $results > $conf['search_results'] )

     {

      if ((($page*$conf['search_results'])-($conf['search_results']*5)) >= 0) 
       $first=($page*$conf['search_results'])-($conf['search_results']*5);
      else 
       $first=0;

      if ((($page*$conf['search_results'])+($conf['search_results']*6)) <= $results) 
       $last =($page*$conf['search_results'])+($conf['search_results']*6);
      else 
       $last = $results;

      @    $i=$first/$conf['search_results'];

      // Previous
      if ($page > 0)
       {
	$pagenum = $page - 1;
	echo ' <a href="' . URL . '/admin/findusers.php?page=' . $pagenum . '&' . $searchURL . '">' . $lang['Previous'] . '</a> | ';
       }

      // Pagination
      for ( $step = $first; $step < $last; $step=$step+$conf['search_results'] )
       {

	if ( $i == $page )

 	 {

	  $pagenum = $i+1;
	  echo ' <span class="warning">' . $pagenum . '</span> | ';
	  $i++;

	 }

	else

	 {

	  $pagenum = $i+1;
	  echo ' <a href="' . URL . '/admin/findusers.php?page=' . $i . '&' . $searchURL . '">' . $pagenum . '</a> | ';
	  $i++;

	 }

       }

      // Next
      if ($page - (($results / $conf['search_results']) - 1) < 0)
       {
	$pagenum = $page+1;
	echo ' <a href="' . URL . '/admin/findusers.php?page=' . $pagenum . '&' . $searchURL . '">' . $lang['Next'] . '</a>';
       }

     }

    // Pagination : END

    echo table_footer ();

   }

  // Output the Find a Realtor form

  echo table_header ( $lang['Realtor_Search'] );

  echo '
   <form action="' . URL . '/admin/findusers.php" method="POST">
    <table width="100%" cellpadding="5" cellspacing="0" border="0">
       ';

  echo userform ($lang['Realtor_Approved'], '<input type="checkbox" name="realtor_approved" value="YES">');
  echo userform ($lang['Realtor_Show_Updated'], '<input type="checkbox" name="realtor_updated" value="YES"> ' . $lang['Realtor_Show_Updated_For_The_Last'] . ' <input type="text" size="3" name="realtor_updated_days" value="5" maxlength="3">' . $lang['days']);
 
  echo userform ($lang['Realtor_First_Name'], '<input type="text" size="45" name="realtor_first_name" maxlength="20">');
  echo userform ($lang['Realtor_Last_Name'], '<input type="text" size="45" name="realtor_last_name" maxlength="20">');
  echo userform ($lang['Realtor_Company_Name'], '<input type="text" size="45" name="realtor_company_name" maxlength="20">');
  echo userform ($lang['Search_Keyword'], '<input type="text" size="45" name="realtor_description" maxlength="100">');
  echo userform ($lang['Location'], '<select name="realtor_location"><option value="ANY" SELECTED>' . $lang['Search_Any'] . ' ' . $lang['Location'] . '</option>' . generate_options_list(LOCATIONS_TABLE) . '</select>');
  echo userform ($lang['City'], '<input type="text" size="45" name="realtor_city" maxlength="15">');
  echo userform ($lang['Realtor_Address'], '<input type="text" size="45" name="realtor_address" maxlength="50">');
  if (strcasecmp($conf['show_postal_code'], 'OFF'))
    echo userform ($lang['Zip_Code'], '<input type="text" size="45" name="realtor_zip_code" maxlength="10">');
  echo userform ($lang['Realtor_Phone'], '<input type="text" size="45" name="realtor_phone" maxlength="15">');
  echo userform ($lang['Realtor_Fax'], '<input type="text" size="45" name="realtor_fax" maxlength="15">');
  echo userform ($lang['Realtor_Mobile'], '<input type="text" size="45" name="realtor_mobile" maxlength="15">');
  
  echo userform ($lang['Realtor_e_mail'], '<input type="text" size="45" name="realtor_e_mail" maxlength="30">');
  echo userform ($lang['Realtor_Website'], '<input type="text" size="45" name="realtor_website" maxlength="50">');
  echo userform ($lang['Realtor_Login'], '<input type="text" size="45" name="realtor_login" maxlength="50">');
 
  echo userform ('', '<input type="Submit" name="realtor_search" value="' . $lang['Realtor_Search'] . '">');

  echo '
    </table>
   </form>
       ';

  echo table_footer ();

 }

else

 error ('Critical Error' , 'Please, login to access this script.');

// Template footer
include ( PATH . '/admin/template/footer.php' );

?>